package com.net.module.service.impl;

import com.net.module.entity.Orders;
import com.net.module.mapper.OrdersMapper;
import com.net.module.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.net.utils.HTTPUtil;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 猿仁
 * @since 2023-03-02
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    /**
     * 下单
     * 模拟事务场景，实际业务和表设计并不是如此
     *
     * @param orders
     * @param inventoryId 库存id
     * @return
     * @author tianyu.Ge
     * @date 2023/3/2 16:50
     */
    @GlobalTransactional
    @Override
    public boolean placeAnOrder(Long inventoryId, Orders orders) {
        System.out.println("account XID " + RootContext.getXID());
        if (orders.getNumber() == null || orders.getNumber() != 1) {
            throw new RuntimeException("订单数量只能选1个！");
        }
        // 新增订单
        boolean save = save(orders);
        // 调用库存-1接口(将XID传递给下一个接口，或者其他服务，让对应的服务读取Header请求头XID被全局事务进行管理)
        Boolean boyd = HTTPUtil.seataGetFrom("http://127.0.0.1:8091/api/inventory/inventorySubOne/" + inventoryId, new HashMap() {{
            put("message", "请检查是否异常！");
        }}, Boolean.class);
        // 场景1,库存失败
        if (!boyd) {
            throw new RuntimeException("库存扣除失败，请查看详情！");
        } else {
            if (boyd) {
                // 场景2，库存成功,业务处理异常...
                throw new RuntimeException("订单业务处理繁忙，请稍后再试！");
            }
        }
        return save;
    }
}
